<template>
  <div class="login-container">
    <!-- 顶部 -->
    <div class="absolute top-0 right-0 flex items-center justify-end px-25 h-20">
      <el-switch
        v-model="isDark"
        inline-prompt
        :active-icon="IconEpMoon"
        :inactive-icon="IconEpSunny"
        active-color="var(--el-fill-color-dark)"
        inactive-color="var(--el-color-primary)"
        @change="handleThemeChange"
      />
      <lang-select class="ml-4 cursor-pointer" />
    </div>
    <!-- 登录表单 -->
    <el-card class="z-1 !border-none w-100 !bg-transparent !rounded-4% <sm:w-83">
      <div class="text-center relative">
        <h1>登录</h1>
      </div>
      <el-form ref="loginFormRef" :model="loginData" :rules="loginRules" class="login-form">
        <el-form-item prop="username">
          <div class="p-2">
            <svg-icon icon-class="user" />
          </div>
          <el-input
            ref="username"
            v-model="loginData.username"
            class="flex-1"
            size="large"
            placeholder="用户名"
            name="username"
          />
        </el-form-item>

        <el-tooltip :disabled="isCapslock === false" content="Caps lock is On" placement="right">
          <el-form-item prop="password">
            <span class="p-2">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              v-model="loginData.password"
              class="flex-1"
              placeholder="密码"
              :type="passwordVisible === false ? 'password' : 'input'"
              size="large"
              name="password"
              @keyup="checkCapslock"
              @keyup.enter="handleLogin"
            />
            <span class="mr-2" @click="passwordVisible = !passwordVisible">
              <svg-icon
                :icon-class="passwordVisible === false ? 'eye' : 'eye-open'"
                class="cursor-pointer"
              />
            </span>
          </el-form-item>
        </el-tooltip>

        <!-- 验证码 -->
        <el-form-item prop="verifyCode">
          <span class="p-2">
            <svg-icon icon-class="verify-code" />
          </span>

          <el-input
            v-model="loginData.verifyCode"
            auto-complete="off"
            placeholder="验证码"
            class="w-[60%]"
            @keyup.enter="handleLogin"
          />

          <div class="captcha">
            <el-image
              :src="captchaBase64"
              class="w-[120px] h-[48px] cursor-pointer"
              @click="getCaptcha"
            >
              <template #error>
                <div class="image-slot">
                  <i-ep-picture />
                </div>
              </template>
            </el-image>
          </div>
        </el-form-item>

        <el-button :loading="loading" type="primary" class="w-full" @click.prevent="handleLogin"
          >确认
        </el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import router from '@/router'
import LangSelect from '@/components/LangSelect/index.vue'
import SvgIcon from '@/components/SvgIcon/index.vue'
import IconEpSunny from '~icons/ep/sunny'
import IconEpMoon from '~icons/ep/moon'

// 状态管理依赖
import { useUserStore, useAppStore, useSettingsStore } from '@/store'

// API依赖
import { LocationQuery, LocationQueryValue, useRoute } from 'vue-router'
import { getCaptchaApi } from '@/api/auth'
import { LoginData } from '@/api/auth/types'

/**
 * 明亮/暗黑主题切换
 */
const settingsStore = useSettingsStore()
const isDark = ref<boolean>(settingsStore.theme === 'dark')
const handleThemeChange = (isDark: any) => {
  useToggle(isDark)
  settingsStore.changeSetting({
    key: 'theme',
    value: isDark ? 'dark' : 'light'
  })
}

const loading = ref(false) // 按钮loading
const isCapslock = ref(false) // 是否大写锁定
const passwordVisible = ref(false) // 密码是否可见
const captchaBase64 = ref() // 验证码图片Base64字符串
const loginFormRef = ref(ElForm) // 登录表单ref

const loginData = reactive<LoginData>({
  username: 'admin',
  password: '123456'
})

const loginRules = computed(() => {
  return {
    username: [
      {
        required: true,
        trigger: 'blur',
        message: '请输入用户名'
      }
    ],
    password: [
      {
        required: true,
        trigger: 'blur',
        message: '请输入密码'
      },
      {
        min: 6,
        message: '最小6位数',
        trigger: 'blur'
      }
    ],
    captchaCode: [
      {
        required: true,
        trigger: 'blur',
        message: '请输入验证码'
      }
    ]
  }
})

/**
 * 检查输入大小写状态
 */
function checkCapslock(e: any) {
  const { key } = e
  isCapslock.value = key && key.length === 1 && key >= 'A' && key <= 'Z'
}

/**
 * 获取验证码
 */
function getCaptcha() {
  getCaptchaApi().then(({ data }) => {
    const { captchaImgBase64, verifyCodeKey } = data
    loginData.verifyCodeKey = verifyCodeKey
    captchaBase64.value = captchaImgBase64
  })
}

/**
 * 登录
 */
const route = useRoute()
const userStore = useUserStore()
function handleLogin() {
  loginFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true
      userStore
        .login(loginData)
        .then(() => {
          const query: LocationQuery = route.query

          const redirect = (query.redirect as LocationQueryValue) ?? '/'

          const otherQueryParams = Object.keys(query).reduce((acc: any, cur: string) => {
            if (cur !== 'redirect') {
              acc[cur] = query[cur]
            }
            return acc
          }, {})

          router.push({ path: redirect, query: otherQueryParams })
        })
        .catch(() => {
          // 验证失败，重新生成验证码
          getCaptcha()
        })
        .finally(() => {
          loading.value = false
        })
    }
  })
}

onMounted(() => {
  getCaptcha()
})
</script>

<style lang="scss" scoped>
.dark .login-container {
  background: url('@/assets/images/login-bg-dark.jpg') no-repeat center right;
}

.login-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;

  overflow-y: auto;
  background: url('@/assets/images/login-bg.jpg') no-repeat center right;

  .login-form {
    padding: 30px 10px;

    .captcha {
      position: absolute;
      top: 0;
      right: 0;

      .image-slot {
        display: flex;
        align-items: center;
        justify-content: right;
        width: 100%;
        height: 100%;
        font-size: 18px;
        color: var(--el-text-color-secondary);
        background: var(--el-fill-color-light);

        svg {
          margin-right: 10px;
        }
      }
    }
  }
}

.el-form-item {
  background: var(--el-input-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: 5px;
}

:deep(.el-input) {
  .el-input__wrapper {
    padding: 0;
    background-color: transparent;
    box-shadow: none;

    &.is-focus,
    &:hover {
      box-shadow: none !important;
    }

    input:-webkit-autofill {
      transition: background-color 5000s ease-in-out 0s; /* 通过延时渲染背景色变相去除背景颜色 */
    }
  }
}
</style>
